// 模拟学生成绩数据
const studentData = [
    { id: '2023001', name: '张三', chinese: 89, math: 92, english: 88 },
    { id: '2023002', name: '李四', chinese: 76, math: 85, english: 92 },
    { id: '2023003', name: '王五', chinese: 94, math: 96, english: 95 },
    { id: '2023004', name: '赵六', chinese: 65, math: 72, english: 68 },
    { id: '2023005', name: '钱七', chinese: 88, math: 84, english: 90 },
    { id: '2023006', name: '孙八', chinese: 92, math: 88, english: 85 },
    { id: '2023007', name: '周九', chinese: 78, math: 82, english: 75 },
    { id: '2023008', name: '吴十', chinese: 85, math: 90, english: 87 }
];

// 计算总分和平均分
function calculateScores(student) {
    const total = student.chinese + student.math + student.english;
    return {
        ...student,
        total,
        average: (total / 3).toFixed(1)
    };
}

// 计算排名
function calculateRanks(students) {
    return students
        .map(calculateScores)
        .sort((a, b) => b.total - a.total)
        .map((student, index) => ({ ...student, rank: index + 1 }));
}

// 更新统计数据
function updateStats(students) {
    const totalAverage = (students.reduce((sum, student) => 
        sum + parseFloat(student.average), 0) / students.length).toFixed(1);
    
    const passCount = students.filter(student => student.total / 3 >= 60).length;
    const passRate = ((passCount / students.length) * 100).toFixed(0);
    
    const excellentCount = students.filter(student => student.total / 3 >= 85).length;
    const excellentRate = ((excellentCount / students.length) * 100).toFixed(0);

    document.querySelector('.average-score').textContent = totalAverage;
    document.querySelector('.pass-rate').textContent = passRate + '%';
    document.querySelector('.excellent-rate').textContent = excellentRate + '%';
}

// 渲染成绩表格
function renderTable(students) {
    const tbody = document.getElementById('studentTableBody');
    tbody.innerHTML = students.map(student => `
        <tr>
            <td>${student.id}</td>
            <td>${student.name}</td>
            <td>${student.chinese}</td>
            <td>${student.math}</td>
            <td>${student.english}</td>
            <td>${student.total}</td>
            <td>${student.average}</td>
            <td>${student.rank}</td>
        </tr>
    `).join('');
}

// 渲染成绩分布图表
function renderChart(students) {
    const ctx = document.getElementById('scoreDistribution').getContext('2d');
    const scoreRanges = ['<60', '60-70', '70-80', '80-90', '90-100'];
    
    const distribution = students.reduce((acc, student) => {
        const average = student.total / 3;
        if (average < 60) acc[0]++;
        else if (average < 70) acc[1]++;
        else if (average < 80) acc[2]++;
        else if (average < 90) acc[3]++;
        else acc[4]++;
        return acc;
    }, [0, 0, 0, 0, 0]);

    if (window.myChart) {
        window.myChart.destroy();
    }

    window.myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: scoreRanges,
            datasets: [{
                label: '学生人数',
                data: distribution,
                backgroundColor: 'rgba(54, 162, 235, 0.8)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
}

// 搜索功能
function searchStudents(keyword) {
    return calculateRanks(studentData).filter(student =>
        student.id.includes(keyword) ||
        student.name.includes(keyword)
    );
}

// 初始化页面
function initializePage() {
    const rankedStudents = calculateRanks(studentData);
    updateStats(rankedStudents);
    renderTable(rankedStudents);
    renderChart(rankedStudents);

    // 搜索功能事件监听
    const searchInput = document.getElementById('searchInput');
    const searchButton = searchInput.nextElementSibling;

    const handleSearch = () => {
        const keyword = searchInput.value.trim();
        const filteredStudents = keyword ? searchStudents(keyword) : calculateRanks(studentData);
        renderTable(filteredStudents);
        renderChart(filteredStudents);
        updateStats(filteredStudents);
    };

    searchButton.addEventListener('click', handleSearch);
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') handleSearch();
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initializePage);